﻿using System.Threading.Channels;

namespace YarpDemo.Host
{
    public class TrafficHandlerHostedService : BackgroundService
    {
        private readonly ILogger<TrafficHandlerHostedService> _logger;
        private readonly Channel<TrafficContent> _channel;

        public TrafficHandlerHostedService(ILogger<TrafficHandlerHostedService> logger, Channel<TrafficContent> channel)
        {
            _logger = logger;
            _channel = channel;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("Traffic Handler Hosted Service running.");

            try
            {
                while (await _channel.Reader.WaitToReadAsync())
                {
                    if (_channel.Reader.TryRead(out var trafficContent))
                    {
                        _logger.LogWarning($"Traffic: {trafficContent.Host}-{trafficContent.Method}-{trafficContent.Path}-{trafficContent.RequestTime}-{trafficContent.ResponseTime}-{trafficContent.StatusCode}");
                    }
                }
            }
            catch (ChannelClosedException)
            {
                _logger.LogError("Channel was closed");
            }

            _logger.LogInformation("Traffic Handler Hosted Service is stopping.");
        }
    }
}
